package ATBMS.control;

import ATBMS.modles.DAO.DAOFactory;
import ATBMS.modles.DAO.FlightDAO;
import ATBMS.modles.DAO.TicketDAO;
import ATBMS.modles.Flight;
import ATBMS.modles.Ticket;
import ATBMS.modles.User;
import ATBMS.ucm.UCDeleteUser;
import ATBMS.view.user.UserViewInterface;
import ATBMS.view.useredit.EditUserViewImpl;
import ATBMS.view.useredit.UserEditViewInterface;
import java.awt.event.ActionEvent;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * User Controller
 */
public class UserControl {

    private UserViewInterface uv;
    private User currentUser;
    private String userTelphoneNumber;
    static private UserControl instance;

    /**
     * Return static UserControl instance
     * @param user
     * @return
     */
    static public UserControl getInstance(User user) {
        if (instance == null) {
            instance = new UserControl(user);
        }
        return instance;
    }

    /**
     * Creates a new <code>UserControl</code> object
     */
    private UserControl(User user) {
        this.currentUser = user;
    }

    /**
     * Set User View and show tickets
     * @param User View Interface
     */
    public void setUserView(UserViewInterface uv) {
        this.uv = uv;
        refreshFlightTable();
    }

    /**
     * Get User View Interface
     * @return
     */
    public UserViewInterface getUserView() {
        return uv;
    }

    private void refreshFlightTable() {
        uv.setTableMode(UserViewInterface.USERVIEWTABLEMODE_FLIGHTS);
        FlightDAO flightdao = DAOFactory.getFlightDAO();
        List<Flight> flights;
        if (flightdao == null) {
            //uv.alert("Can't Connect To DB!");
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            flights = new ArrayList<Flight>();
            try {
                flights.add(new Flight("CZ6491", "LanZhou", "China Southern airlines",
                        dateFormat.parse("2010-11-05 12:40"), dateFormat.parse("2010-11-05 15:40"),
                        134, "319", (int) Math.random() * 1000 + 2000));
                flights.add(new Flight("CZ6303", "ShenZhen", "China Southern airlines",
                        dateFormat.parse("2010-11-05 14:05"), dateFormat.parse("2010-11-05 18:00"),
                        187, "M90", (int) Math.random() * 1000 + 2000));
                flights.add(new Flight("CZ6309", "ShenZhen", "China Southern airlines",
                        dateFormat.parse("2010-11-05 10:50"), dateFormat.parse("2010-11-05 14:55"),
                        187, "320", (int) Math.random() * 1000 + 2000));
                flights.add(new Flight("CA3503", "ShenZhen", "Air China International",
                        dateFormat.parse("2010-11-05 14:10"), dateFormat.parse("2010-11-05 18:00"),
                        187, "320", (int) Math.random() * 1000 + 2000));
                flights.add(new Flight("ZH9828", "ShenZhen", "Shenzhen Airlines",
                        dateFormat.parse("2010-11-05 14:10"), dateFormat.parse("2010-11-05 18:00"),
                        187, "320", (int) Math.random() * 1000 + 2000));
                flights.add(new Flight("CZ6492", "ShenYang", "China Southern airlines",
                        dateFormat.parse("2010-11-05 23:10"), dateFormat.parse("2010-11-05 01:40"),
                        134, "319", (int) Math.random() * 1000 + 2000));
                flights.add(new Flight("HU7743", "ShenZhen", "Hainan Airlines",
                        dateFormat.parse("2010-11-05 19:00"), dateFormat.parse("2010-11-05 21:10"),
                        189, "738", (int) Math.random() * 1000 + 2000));
                flights.add(new Flight("MU2385", "ShenZhen", "China Eastern Airlines",
                        dateFormat.parse("2010-11-05 7:45"), dateFormat.parse("2010-11-05 11:55"),
                        180, "320", (int) Math.random() * 1000 + 2000));
                flights.add(new Flight("CA3599", "ShenZhen", "Air China International",
                        dateFormat.parse("2010-11-05 13:50"), dateFormat.parse("2010-11-05 18:25"),
                        180, "320", (int) Math.random() * 1000 + 2000));
                flights.add(new Flight("HU7744", "LanZhou", "Hainan Airlines",
                        dateFormat.parse("2010-11-05 7:35"), dateFormat.parse("2010-11-05 10:50"),
                        189, "738", (int) Math.random() * 1000 + 2000));
                flights.add(new Flight("CA3598", "LanZhou", "Air China International",
                        dateFormat.parse("2010-11-05 8:50"), dateFormat.parse("2010-11-05 13:00"),
                        180, "320", (int) Math.random() * 1000 + 2000));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            flights = flightdao.findAll();
        }

        uv.listFlight(flights);
    }

    private void refreshBookedTicketTable() {
        uv.setTableMode(UserViewInterface.USERVIEWTABLEMODE_TICKET);
        TicketDAO ticketdao = DAOFactory.getTicketDAO();

        if (ticketdao == null) {
            uv.alert("Can't Connect To DB!");
            return;
        }
        List<Ticket> tickets = null;
        if (currentUser != null) {
            tickets = ticketdao.findByUserID(currentUser.getUid());
        } else if (userTelphoneNumber != null && !userTelphoneNumber.isEmpty()) {
            tickets = ticketdao.findByTel(userTelphoneNumber);
        }
        if (tickets != null) {
            uv.listTickets(tickets);
        }
    }

    /**
     * Create a Action For User View's Tickets Menu
     * @return Action
     */
    public javax.swing.Action getTicktetsMenuAction() {
        return new javax.swing.AbstractAction() {

            public void actionPerformed(ActionEvent e) {
                if (e.getActionCommand().compareTo("Show Tickets") == 0) {
                    refreshBookedTicketTable();
                } else if (e.getActionCommand().compareTo("Show Flights") == 0) {
                    refreshFlightTable();
                } else if (e.getActionCommand().compareTo("Show This Flight") == 0) {
                    showSelectedFlight();
                } else if (e.getActionCommand().compareTo("Book This Flight") == 0) {
                    bookFlight();
                }
            }
        };
    }

    private void showSelectedFlight() {

        String flightCode = uv.getSelectedFlightCode();
        if (flightCode == null || flightCode.isEmpty()) {
            uv.alert("Please select a flight");
            return;
        }

        FlightDAO flightdao = DAOFactory.getFlightDAO();
        if (flightdao == null) {
            uv.alert("Can't Connect To DB!");
            return;
        }

        Flight flight = flightdao.findByFlightCode(flightCode);
        if (flight == null) {
            uv.alert("Not found the flight!");
            return;
        }
        List<Flight> l = new ArrayList<Flight>();
        l.add(flight);
        uv.setTableMode(UserViewInterface.USERVIEWTABLEMODE_FLIGHTS);
        uv.listFlight(l);
    }

    private void bookFlight() {
        if (uv.getTableMode() != UserViewInterface.USERVIEWTABLEMODE_FLIGHTS) {
            uv.alert("Please select a flight");
            return;
        }

        String flightCode = uv.getSelectedFlightCode();
        if (flightCode == null || flightCode.isEmpty()) {
            uv.alert("Please select a flight");
            return;
        }

        FlightDAO flightdao = DAOFactory.getFlightDAO();
        if (flightdao == null) {
            uv.alert("Can't Connect To DB!");
            return;
        }

        Flight flight = flightdao.findByFlightCode(flightCode);
        if (flight == null) {
            uv.alert("Not found the flight!");
            return;
        }

        String telphoneNumber;
        if (currentUser == null) {
            telphoneNumber = uv.inputDialog("Please input your telephone");
            userTelphoneNumber = telphoneNumber;
        } else {
            telphoneNumber = currentUser.getUtel();
        }

        TicketDAO ticketdao = DAOFactory.getTicketDAO();

        Ticket ticket = new Ticket(flight.getFcode(),
                (currentUser == null ? 0 : currentUser.getUid()),
                new Date(), telphoneNumber);
        if (ticketdao.insert(ticket)) {
            uv.alert("Book succeed!");
            refreshBookedTicketTable();
        } else {
            uv.alert("Book failed!\r\n" + ticketdao.getErrorMessage());
        }
    }

    /**
     * Create a Action For User View's Account Menu
     * @return Action
     */
    public javax.swing.Action getAccountMenuAction() {
        return new javax.swing.AbstractAction() {

            public void actionPerformed(ActionEvent e) {
                if (e.getActionCommand().compareTo("Edit Infomation") == 0) {
                    if (currentUser == null) {
                        uv.alert("You havn't login!");
                        return;
                    }
                    EditUserControl euc = new EditUserControl(currentUser);
                    UserEditViewInterface uev = new EditUserViewImpl(MainApp.getApplication().getMainFrame(), euc, currentUser);
                    euc.setUserEditView(uev);
                    uev.doModal();
                    if (uv.getTableMode() == UserViewInterface.USERVIEWTABLEMODE_TICKET) {
                        refreshBookedTicketTable();
                    }
                } else if (e.getActionCommand().compareTo("Delete Self") == 0) {
                    if (currentUser == null) {
                        uv.alert("You havn't login!");
                        return;
                    }
                    UCDeleteUser ucDU = new UCDeleteUser(UserControl.getInstance(null), currentUser.getUname());
                    ucDU.run();
                }
            }
        };
    }
}
